<template>
  <div class="computer-scrap">
    <div class="header">
      <router-link to="/main/process" class="back-btn">
        <i class="el-icon-arrow-left"></i>
        <span>返回</span>
      </router-link>
      <h2>电脑报废申请流程</h2>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-menu" @click="showList">报废列表</el-button>
      </div>
    </div>

    <div class="content">
      <el-form :model="formData" ref="form" :rules="rules" label-width="120px" class="scrap-form">
        <!-- 基本信息 -->
        <div class="form-section">
          <h3>基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="申请编号" prop="applyNo">
                <el-input v-model="formData.applyNo" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请日期" prop="applyDate">
                <el-date-picker
                  v-model="formData.applyDate"
                  type="date"
                  placeholder="选择申请日期"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="申请部门" prop="department">
                <el-select v-model="formData.department" placeholder="请选择部门" style="width: 100%">
                  <el-option
                    v-for="dept in departments"
                    :key="dept.value"
                    :label="dept.label"
                    :value="dept.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请人" prop="applicant">
                <el-input v-model="formData.applicant"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 设备信息 -->
        <div class="form-section">
          <h3>设备信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="设备编号" prop="deviceNo">
                <el-input v-model="formData.deviceNo"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备类型" prop="deviceType">
                <el-select v-model="formData.deviceType" placeholder="请选择设备类型" style="width: 100%">
                  <el-option label="台式电脑" value="desktop"></el-option>
                  <el-option label="笔记本电脑" value="laptop"></el-option>
                  <el-option label="一体机" value="all-in-one"></el-option>
                  <el-option label="服务器" value="server"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="品牌型号" prop="model">
                <el-input v-model="formData.model"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="配置信息" prop="specification">
                <el-input v-model="formData.specification"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="购置日期" prop="purchaseDate">
                <el-date-picker
                  v-model="formData.purchaseDate"
                  type="date"
                  placeholder="选择购置日期"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="使用年限" prop="usageYears">
                <el-input-number 
                  v-model="formData.usageYears" 
                  :min="0" 
                  :max="20"
                  style="width: 200px">
                </el-input-number>
                <span class="unit">年</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 报废信息 -->
        <div class="form-section">
          <h3>报废信息</h3>
          <el-form-item label="报废原因" prop="scrapReason">
            <el-select v-model="formData.scrapReason" placeholder="请选择报废原因" style="width: 100%">
              <el-option label="设备老化，性能下降" value="aging"></el-option>
              <el-option label="故障维修成本过高" value="repair-cost"></el-option>
              <el-option label="配置落后，无法满足需求" value="outdated"></el-option>
              <el-option label="重大故障无法修复" value="unrepairable"></el-option>
              <el-option label="其他原因" value="other"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="详细说明" prop="description">
            <el-input
              type="textarea"
              v-model="formData.description"
              :rows="4"
              placeholder="请详细描述报废原因和设备现状">
            </el-input>
          </el-form-item>

          <el-form-item label="故障描述" prop="faultDescription">
            <el-input
              type="textarea"
              v-model="formData.faultDescription"
              :rows="4"
              placeholder="请详细描述设备故障情况">
            </el-input>
          </el-form-item>

          <el-form-item label="维修记录" prop="repairHistory">
            <el-table
              :data="formData.repairHistory"
              border
              style="width: 100%">
              <el-table-column prop="date" label="维修日期" width="180"></el-table-column>
              <el-table-column prop="fault" label="故障现象"></el-table-column>
              <el-table-column prop="solution" label="维修方案"></el-table-column>
              <el-table-column prop="cost" label="维修费用" width="120"></el-table-column>
              <el-table-column label="操作" width="120">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="removeRepairRecord(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px;">
              <el-button type="primary" size="small" @click="addRepairRecord">添加维修记录</el-button>
            </div>
          </el-form-item>
        </div>

        <!-- 处置建议 -->
        <div class="form-section">
          <h3>处置建议</h3>
          <el-form-item label="处置方式" prop="disposalMethod">
            <el-radio-group v-model="formData.disposalMethod">
              <el-radio label="recycle">回收处理</el-radio>
              <el-radio label="transfer">资产转让</el-radio>
              <el-radio label="dismantle">拆解利用</el-radio>
              <el-radio label="other">其他方式</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="处置说明" prop="disposalDescription" v-if="formData.disposalMethod === 'other'">
            <el-input
              type="textarea"
              v-model="formData.disposalDescription"
              :rows="3"
              placeholder="请说明具体处置方式">
            </el-input>
          </el-form-item>
        </div>

        <!-- 附件信息 -->
        <div class="form-section">
          <h3>附件信息</h3>
          <el-form-item label="相关附件" prop="attachments">
            <el-upload
              action="/api/file/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              multiple
              :limit="5"
              :file-list="formData.attachments">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                可上传设备照片、检测报告等相关文件，单个文件不超过10MB
              </div>
            </el-upload>
          </el-form-item>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="submitForm">提交申请</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </el-form>
    </div>

    <!-- 添加维修记录对话框 -->
    <el-dialog title="添加维修记录" :visible.sync="repairDialogVisible" width="50%">
      <el-form :model="repairForm" ref="repairForm" :rules="repairRules" label-width="100px">
        <el-form-item label="维修日期" prop="date">
          <el-date-picker
            v-model="repairForm.date"
            type="date"
            placeholder="选择维修日期"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="故障现象" prop="fault">
          <el-input v-model="repairForm.fault" type="textarea" :rows="2"></el-input>
        </el-form-item>
        <el-form-item label="维修方案" prop="solution">
          <el-input v-model="repairForm.solution" type="textarea" :rows="2"></el-input>
        </el-form-item>
        <el-form-item label="维修费用" prop="cost">
          <el-input-number v-model="repairForm.cost" :min="0" :precision="2"></el-input-number>
          <span class="unit">元</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="repairDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddRepair">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 报废列表对话框 -->
    <el-dialog title="报废申请列表" :visible.sync="listDialogVisible" width="80%">
      <div class="filter-section">
        <el-input
          v-model="searchQuery"
          placeholder="请输入申请编号/申请人"
          style="width: 200px"
          clearable
          @input="handleSearch">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        
        <el-select v-model="statusFilter" placeholder="申请状态" clearable @change="handleSearch">
          <el-option label="待审批" value="pending"></el-option>
          <el-option label="已通过" value="approved"></el-option>
          <el-option label="已拒绝" value="rejected"></el-option>
          <el-option label="已取消" value="cancelled"></el-option>
        </el-select>
        
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleSearch">
        </el-date-picker>
      </div>
      
      <el-table :data="filteredList" border style="width: 100%">
        <el-table-column prop="applyNo" label="申请编号" width="180"></el-table-column>
        <el-table-column prop="department" label="申请部门" width="150"></el-table-column>
        <el-table-column prop="applicant" label="申请人" width="120"></el-table-column>
        <el-table-column prop="applyDate" label="申请日期" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.applyDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="deviceCount" label="设备数量" width="100" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="viewDetail(scope.row)">查看</el-button>
            <el-button 
              size="mini" 
              type="primary" 
              v-if="scope.row.status === 'pending'"
              @click="editScrap(scope.row)">
              编辑
            </el-button>
            <el-button 
              size="mini" 
              type="danger"
              v-if="scope.row.status === 'pending'"
              @click="cancelScrap(scope.row)">
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ComputerScrapProcess',
  data() {
    return {
      formData: {
        applyNo: this.generateApplyNo(),
        applyDate: new Date(),
        department: '',
        applicant: '',
        deviceNo: '',
        deviceType: '',
        model: '',
        specification: '',
        purchaseDate: '',
        usageYears: 0,
        scrapReason: '',
        description: '',
        faultDescription: '',
        repairHistory: [],
        disposalMethod: 'recycle',
        disposalDescription: '',
        attachments: []
      },
      departments: [
        { value: 'tech', label: '技术部' },
        { value: 'hr', label: '人力资源部' },
        { value: 'finance', label: '财务部' },
        { value: 'admin', label: '行政部' },
        { value: 'engineering', label: '工程部' },
      ],
      rules: {
        department: [{ required: true, message: '请选择申请部门', trigger: 'change' }],
        applicant: [{ required: true, message: '请输入申请人', trigger: 'blur' }],
        deviceNo: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
        deviceType: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
        model: [{ required: true, message: '请输入品牌型号', trigger: 'blur' }],
        purchaseDate: [{ required: true, message: '请选择购置日期', trigger: 'change' }],
        scrapReason: [{ required: true, message: '请选择报废原因', trigger: 'change' }],
        description: [{ required: true, message: '请填写详细说明', trigger: 'blur' }]
      },
      repairDialogVisible: false,
      repairForm: {
        date: '',
        fault: '',
        solution: '',
        cost: 0
      },
      repairRules: {
        date: [{ required: true, message: '请选择维修日期', trigger: 'change' }],
        fault: [{ required: true, message: '请输入故障现象', trigger: 'blur' }],
        solution: [{ required: true, message: '请输入维修方案', trigger: 'blur' }]
      },
      listDialogVisible: false,
      searchQuery: '',
      statusFilter: '',
      dateRange: null,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      filteredList: []
    }
  },
  methods: {
    generateApplyNo() {
      const date = new Date()
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
      return `BF${year}${month}${day}${random}`
    },
    addRepairRecord() {
      this.repairForm = {
        date: '',
        fault: '',
        solution: '',
        cost: 0
      }
      this.repairDialogVisible = true
    },
    confirmAddRepair() {
      this.$refs.repairForm.validate(valid => {
        if (valid) {
          this.formData.repairHistory.push({...this.repairForm})
          this.repairDialogVisible = false
        }
      })
    },
    removeRepairRecord(index) {
      this.formData.repairHistory.splice(index, 1)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleRemove(file, fileList) {
      this.formData.attachments = fileList
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    async submitForm() {
      try {
        await this.$refs.form.validate()
        // TODO: 发送请求到后端
        this.$message.success('申请提交成功')
        this.$router.push('/main/process')
      } catch (error) {
        this.$message.error(error.message || '请填写完整的申请信息')
      }
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.formData.applyNo = this.generateApplyNo()
      this.formData.applyDate = new Date()
      this.formData.repairHistory = []
      this.formData.attachments = []
    },
    showList() {
      this.listDialogVisible = true
      this.loadScrapList()
    },
    async loadScrapList() {
      try {
        // TODO: 调用API获取列表数据
        this.filteredList = [
          {
            applyNo: 'BF202403010001',
            department: '技术部',
            applicant: '张三',
            applyDate: '2024-03-01',
            deviceCount: 2,
            status: 'pending'
          },
          // ... 更多测试数据
        ]
        this.total = this.filteredList.length
      } catch (error) {
        this.$message.error('加载列表失败')
      }
    },
    handleSearch() {
      let results = [...this.filteredList]
      
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        results = results.filter(item => 
          item.applyNo.toLowerCase().includes(query) ||
          item.applicant.toLowerCase().includes(query)
        )
      }
      
      if (this.statusFilter) {
        results = results.filter(item => item.status === this.statusFilter)
      }
      
      if (this.dateRange) {
        // 实现日期筛选逻辑
      }
      
      this.total = results.length
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.filteredList = results.slice(start, end)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.handleSearch()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.handleSearch()
    },
    getStatusType(status) {
      const typeMap = {
        pending: 'warning',
        approved: 'success',
        rejected: 'danger',
        cancelled: 'info'
      }
      return typeMap[status] || ''
    },
    getStatusText(status) {
      const textMap = {
        pending: '待审批',
        approved: '已通过',
        rejected: '已拒绝',
        cancelled: '已取消'
      }
      return textMap[status] || status
    },
    formatDate(date) {
      return new Date(date).toLocaleDateString()
    },
    viewDetail(row) {
      // 将数据填充到表单中并设置为只读
      this.formData = {
        ...row,
        deviceType: row.deviceType || '',
        deviceNo: row.deviceNo || '',
        purchaseDate: row.purchaseDate || '',
        specifications: row.specifications || '',
        repairHistory: row.repairHistory || [],
        attachments: row.attachments || []
      }
      
      // 设置表单为只读
      this.$nextTick(() => {
        const formItems = this.$refs.form.$el.querySelectorAll('.el-input__inner, .el-textarea__inner')
        formItems.forEach(item => {
          item.setAttribute('readonly', true)
        })
        
        // 禁用所有按钮
        const buttons = this.$refs.form.$el.querySelectorAll('.el-button:not(.el-button--text)')
        buttons.forEach(button => {
          button.setAttribute('disabled', true)
        })
      })
      
      // 关闭列表对话框
      this.listDialogVisible = false
    },
    editScrap(row) {
      // 将数据填充到表单中
      this.formData = {
        ...row,
        deviceType: row.deviceType || '',
        deviceNo: row.deviceNo || '',
        purchaseDate: row.purchaseDate || '',
        specifications: row.specifications || '',
        repairHistory: row.repairHistory || [],
        attachments: row.attachments || []
      }
      
      // 确保表单可编辑
      this.$nextTick(() => {
        const formItems = this.$refs.form.$el.querySelectorAll('.el-input__inner, .el-textarea__inner')
        formItems.forEach(item => {
          item.removeAttribute('readonly')
        })
        
        // 启用所有按钮
        const buttons = this.$refs.form.$el.querySelectorAll('.el-button')
        buttons.forEach(button => {
          button.removeAttribute('disabled')
        })
      })
      
      // 关闭列表对话框
      this.listDialogVisible = false
    },
    cancelScrap(row) {
      this.$confirm('确认取消该报废申请？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 调用取消API
        this.$message.success('已取消')
        this.loadScrapList()
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.computer-scrap {
  padding: 20px;

  .header {
    margin-bottom: 30px;
    position: relative;
    text-align: center;

    .back-btn {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      text-decoration: none;
      color: #606266;
      display: flex;
      align-items: center;
    }

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }

    .header-actions {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .content {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

    .scrap-form {
      max-width: 1000px;
      margin: 0 auto;
    }
  }

  .form-section {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #EBEEF5;

    &:last-child {
      border-bottom: none;
    }

    h3 {
      margin: 0 0 20px;
      padding-left: 10px;
      border-left: 4px solid #409EFF;
      font-size: 18px;
      font-weight: 500;
      color: #303133;
    }
  }

  .form-actions {
    text-align: center;
    margin-top: 40px;
  }

  .unit {
    margin-left: 10px;
    color: #606266;
  }

  .el-upload__tip {
    color: #909399;
  }

  :deep(.el-form-item.is-required .el-form-item__label:before) {
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
  }

  .filter-section {
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
    align-items: center;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 